import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
// Import for Android features.
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
import 'package:webviewdemo/qgWebViewPage.dart';

import 'gqWebViewFunc.dart';

class GQWebView extends StatefulWidget {
  final String? url;
  final String? content;
  final String? title;
  final String? userAgent;

  GQWebView({Key? key, this.url, this.title, this.userAgent, this.content}) : super(key: key);

  @override
  State<StatefulWidget> createState() => GQWebViewState();
}

class GQWebViewState extends State<GQWebView> {
  WebViewController _controller = WebViewController();
  WebViewController? webViewController;
  bool showLoading = true;
  bool showError = false;
  String? loadingUrl;

  @override
  void didUpdateWidget(covariant GQWebView oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    super.initState();
    // if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView(); //兼容键盘弹出来
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      //iOS webKit开启视频播放allowsInlineMediaPlayback: true,
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }
    _controller = WebViewController.fromPlatformCreationParams(params);

    //判断是 Android 平台的 WebView
    if (WebViewPlatform.instance is AndroidWebViewPlatform) {
      final AndroidWebViewController androidController =
          _controller.platform as AndroidWebViewController;
      //处理文件选择，只有 AndroidWebViewController 才暴露出 setOnShowFileSelector 方法，这里才能监听文件选择
    }

    _controller.setJavaScriptMode(JavaScriptMode.unrestricted);
    _controller.setUserAgent(widget.userAgent);
    getJavascriptChannels(context, _controller); //注册js和原生通信
    _controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(onProgress: (int progress) {
        debugPrint('WebView is loading (progress : $progress%)');
      }, onPageStarted: (String url) {
        loadingUrl = url;
        debugPrint('WebView is  (onPageStarted : $url)');
      }, onPageFinished: (String url) {
        debugPrint('Page finished loading: $url');
        webViewController = _controller;
        setState(() {
          showLoading = false;
        });
      }, onWebResourceError: (WebResourceError error) async {
        // String url = await _controller.currentUrl() as String;

        // String jsonStr = jsonEncode(error);
        // Map map = json.decode(jsonStr);
        // var sss = AndroidWebResourceError();
        // sss.failingUrl
        if (loadingUrl == widget.url && error.errorType != WebResourceErrorType.unknown) {
          //开始页面报错，显示报错view
          var state = context.findAncestorStateOfType<GQWebViewPageState>();
          state?.showTitleBarInError(true);
          setState(() {
            showError = true;
            showLoading = false;
          });
        }
        setState(() {
          showLoading = false;
        });
        debugPrint('WebView is error: $WebResourceError');
      }, onNavigationRequest: (NavigationRequest request) {
        return NavigationDecision.navigate;
      }));

    if (widget.url!.contains("images/test.html")) {
      //加载本地html
      _controller.loadFlutterAsset("images/test.html");
    } else {
      _controller.loadRequest(Uri.parse(widget.url ?? ""));
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        WebViewWidget(
          controller: _controller,
        ),
        if (showLoading)
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(8)),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withAlpha(25), // 阴影的颜色
                  blurRadius: 20.0, // 高斯的标准偏差与盒子的形状卷积。
                ),
              ],
            ),
            child: Image.asset(
              "images/loading.gif",
              height: 40.0,
              width: 40.0,
              fit: BoxFit.fill,
            ),
          ),
      ],
    );
  }

  /// 后退方法
  Future<bool> goBack() async {
    if (await _controller.canGoBack() == true) {
      if(Platform.isAndroid&&loadingUrl?.contains("/course/alive")==true){
        return false;
      }else{
        await _controller.goBack();
        return true;
      }
    }
    return false;
  }

  ///前进方法
  Future<bool> forward() async {
    if (await _controller.canGoForward() == true) {
      await _controller.goForward();
      return true;
    }
    return false;
  }

}
